package com.learn.demo.netty.rpc.netty;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;
import lombok.extern.slf4j.Slf4j;

import java.lang.reflect.Proxy;
import java.util.Objects;
import java.util.concurrent.*;

/**
 * Netty客户端
 *
 * @author banjiawei
 * @date 2022/03/11
 */
@Slf4j
public class NettyClient {
    //    private static ExecutorService executorService = new ThreadPoolExecutor(Runtime.getRuntime().availableProcessors(),
//            Runtime.getRuntime().availableProcessors()*2,
//            1,
//            TimeUnit.HOURS,
//            new LinkedBlockingQueue<>(1024),
//            new DefaultThreadFactory("NettyClientPool"));
    private static ExecutorService executorService = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors());
    private static volatile NettyClientHandler clientHandler;

    /**
     * 获取一个客户端代理对象
     *
     * @param serverClass
     * @param providerName
     * @return java.lang.Object
     * @author banjiawei
     * @date 2022/3/11
     */
    public Object getBean(final Class<?> serverClass, final String providerName) {
        return Proxy.newProxyInstance(Thread.currentThread().getContextClassLoader(),
                new Class<?>[]{serverClass}, (proxy, method, args) -> {
                    //客户端每调用一次hello，就会进入到该代码块
                    synchronized (this) {
                        if (Objects.isNull(clientHandler)) {
                            initClient();
                        }
                    }
                    //设置发送给服务器端的参数,providerName为协议头， args[0]是客户端调用API sayHello时的参数
                    clientHandler.setParams(providerName + args[0]);
                    return executorService.submit(clientHandler).get();
                });
    }

    /**
     * 初始化客户端
     *
     * @param
     * @return void
     * @author banjiawei
     * @date 2022/3/11
     */
    private synchronized static void initClient() {
        clientHandler = new NettyClientHandler();
        EventLoopGroup eventLoopGroup = new NioEventLoopGroup();
        Bootstrap bootstrap = new Bootstrap();
        bootstrap.group(eventLoopGroup)
                .channel(NioSocketChannel.class)
                .option(ChannelOption.TCP_NODELAY, true)
                .handler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    protected void initChannel(SocketChannel ch) throws Exception {
                        ChannelPipeline pipeline = ch.pipeline();
                        pipeline.addLast(new StringDecoder());
                        pipeline.addLast(new StringEncoder());
                        pipeline.addLast(clientHandler);
                    }
                });
        try {
            bootstrap.connect("127.0.0.1", 5555).sync();
        } catch (InterruptedException e) {
            log.error("初始化客户端失败", e);
        }
    }
}
